#!/usr/bin/env node
// -*- mode: js -*-
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2019, Joyent, Inc.
 */

var child_process = require('child_process');
var fs = require('fs');
var path = require('path');



///--- Globals

var DIRS = [
    'deps',
    'docs',
    'docs/media',
    'lib',
    'smf',
    'smf/manifests',
    'test',
    'tools'
];

var SUBMODULES = {
    'eng': 'https://github.com/joyent/eng.git',
    'javascriptlint': 'https://github.com/davepacheco/javascriptlint.git',
    'jsstyle': 'https://github.com/davepacheco/jsstyle.git',
    'restdown': 'https://github.com/trentm/restdown.git'
};



///--- Internal Functions

function usage(code, message) {
    if (message)
        console.error(message);

    console.error('usage: %s [repo ...]', path.basename(process.argv[1]));
    process.exit(code);
}


function ensureDirectoryNotExists(dir) {
    try {
        var stats = fs.statSync(dir);
        usage(1, dir + ' already exists');
    } catch (e) {
        return false;
    }
}


function cp(src, dest) {
    fs.createReadStream(src).pipe(fs.createWriteStream(dest));
}


function exec(cmd, dir, cb) {
    child_process.exec(cmd, {cwd: dir}, function (err, stdout, stderr) {
        if (err)
            process.exit(err.code || 1);

        if (typeof (cb) === 'function')
            return cb(null);
    });
}


function mkdir(d) {
    fs.mkdirSync(d, '0750');
}

function gitify(dir, repo) {
    exec('git init', dir, function () {
        exec('git remote add origin git@github.com:joyent/' + repo + '.git',
	    dir);

        Object.keys(SUBMODULES).forEach(function (k) {
            // stub out the git submodule call
            console.error('Cloning into deps/' + k + '...');
            exec('git submodule add ' + SUBMODULES[k] + ' ./deps/' + k, dir);
        });
    });
}



///--- Mainline

if (process.argv.length < 3)
    usage(1, 'repo required');

process.argv.slice(2).forEach(function (arg) {
    var repo = path.resolve(arg);
    ensureDirectoryNotExists(repo);
    mkdir(repo);
    DIRS.concat('.').forEach(function (d) {
        var dir = repo + '/' + d;
        if (d != '.')
            mkdir(dir);

        fs.readdirSync('./' + d).forEach(function (f) {
            var src = './' + d + '/' + f;
            var dest = dir + '/' + f;
            if (fs.statSync(src).isFile() && !/^\..*/.test(f))
                cp(src, dest);
        });
    });

    cp('./.gitignore', repo + '/.gitignore');
    gitify(repo, arg);
});
